const timeutil = require('./timeutil.js');
let Config = require('../core/config.js');

function GetOpenData() {
  return new Promise(function (resolve, reject) {
    //let SevDomain = Config.SevDomain;
    //console.log(Config)
    wx.login({
      success: res => {
        // console.log(res)
        wx.request({
          url: Config.SevDomain + 'WxOpenData',
          data: {
            js_code: res.code
          },
          success: _res => {
            let tres = JSON.parse(_res.data.data);
            //console.log(tres)
            wx.setStorageSync('userinfo', tres);
            console.log('--缓存设置成功--');
            console.log(tres.openid)
            resolve(tres.openid);
            //console.log(_res.data.data)
          },
          fail: _res => {
            console.log('--缓存设置失败--')
            reject({
              msg: 'OPENDATA_GET_FAILURE'
            })
          }
        })
      }
    })
  })


}

function UploadImage(path) {
  return new Promise(function (resolve, reject) {
    //回调函数
    wx.uploadFile({
      filePath: path,
      name: 'file',
      url: Config.SevDomain + '/wxuploader',
      success(res) {
        console.log(res)
        let rdata = res.data;
        //console.log(JSON.parse(rdata))
        let jsonstr = rdata.substring(rdata.indexOf("data") + 7, rdata.length - 2);

        let reg = /\\/g;
        //使用replace方法将全部匹配正则表达式的转义符替换为空
        jsonstr = jsonstr.replace(reg, '');
        let tres = JSON.parse(jsonstr);
        var tdata = {};
        tdata.fileID = Config.SevDomain + tres.httpPath
        resolve(tdata);

      },
      fail(res) {
        console.log(res)
        reject({
          msg: 'FAILED_TO_UPLOAD_IMG'
        })
      }
    })
  })
}

function UpCircleInfo(_res) {
  let app = getApp();
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain + '/circle',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        create_time: timeutil.TimeCode(new Date()),
        update_time: timeutil.TimeCode(new Date()),
        content: _res.content,
        images: _res.realList,
        userid: app.globalData.userid,
        thumbsnum: 0,
        remarksnum: 0,
        nickname: _res.userinfo.nickName,
        avatar: _res.userinfo.avatarUrl,
        location:_res.location || null
      },
      success: res => {
        let rdata = JSON.parse(res.data);
        //console.log(JSON.parse(rdata))

        resolve(rdata.data)
      },
      fail(res) {
        console.log(res)
        reject({
          msg: 'UPLOAD_CIRCLE_INFO_FAILED'
        });
      }
    })
  })
  
}
function QueryCircleInfo(skipstep) {
  //查询
  let app = getApp();
  let mynickname = app.globalData.userInfo.nickName;
  if(Config.Version=='v1'){
    return new Promise(function(resolve,reject){
      wx.request({
        url: Config.SevDomain+'circle',
        method:'GET',
        data:{
          page:parseInt(skipstep/3) + parseInt(skipstep%3)
        },
        success:res=>{
          //console.log(res.data)
          //console.log(res)
          var tdata = JSON.parse(res.data).data;
          tdata.forEach(element => {
            element.images = element.images.split(',')
            element._id = element.id
          });
          //console.log(tdata)
          resolve({data:tdata})
        },fail:res=>{
          reject({
            msg: 'FAILED_TO_GET_CIRCLE_LIST'
          })
        }
      })
    })
  }else if(Config.Version=='v2'){
    return new Promise(function(resolve,reject){
      wx.request({
        url: Config.SevDomain+'circlepart',
        method:'GET',
        data:{
          page:parseInt(skipstep/3) + parseInt(skipstep%3)
        },
        success:res=>{
          
          var tdata = JSON.parse(res.data).data;
         // console.log(tdata)
          tdata.forEach(element => {
            element.images = element.circlePO.images.split(',')
            element.id = element.circlePO.id
            element.content = element.circlePO.content
            element.location = element.circlePO.location
            element.avatar = element.circlePO.avatar
            element.nickname = element.circlePO.nickname
            element.updatetime = element.circlePO.updatetime
            if(element.thumbPOList.indexOf(mynickname)==-1){
              element.liked = false;
            }else{
              element.liked = true;
            }
            element.thumblist = element.thumbPOList.toString();

          });
          //console.log(tdata)
          resolve({data:tdata})
        },fail:res=>{
          reject({
            msg: 'FAILED_TO_GET_CIRCLE_LIST'
          })
        }
      })
    })
  }
  
}
function GetOneCircleInfo(cid){
  return new Promise(function(resolve,reject){
    //返回单一查询结果
    wx.request({
      url: Config.SevDomain+'circle/'+cid,
      method:'GET',
      success:res=>{
        //console.log(res.data)
        //console.log(res)
        var tdata = JSON.parse(res.data).data;
        //console.log(tdata);
        let rdata = tdata;
        rdata.images = rdata.images.split(',');
        rdata._id = rdata.id
        tdata = rdata;
        //console.log(tdata)
        resolve({data:tdata})
      },fail:res=>{
        reject({
          msg: 'FAILED_TO_GET_CIRCLE_LIST'
        })
      }
    })
  })
}

function GetCommentInfo(cid){
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'remark',
      method:'GET',
      data:{
        circleid:cid
      },
      success:res=>{
        let ans = JSON.parse(res.data).data;
        //console.log(ans)
        resolve({data:ans})
      },
      fail:res=>{
        reject({msg:'FAILED_TO_LOAD_COMMENT'});
      }
    })
  })
}
function GetThumbInfo(cid){
  let app = getApp();
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'/thumb',
      method:'GET',
      data:{
        userid: app.globalData.userid,
        circleid: cid
      },
      success:res=>{
        let ans = JSON.parse(res.data).data;
        //console.log(ans)
        resolve({data:ans})
      },
      fail:res=>{
        reject({msg:'FAILED_TO_GET_LIKE'});
      }
    })
  })
}
function UpCommentInfo(cid, commentText, replyid,replynickname) {
//  console.log(replyid)
  let app = getApp();
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain + '/remark',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        create_time: timeutil.TimeCode(new Date()),
        circleid: cid,
        nickname: app.globalData.userInfo.nickName,
        avatar: app.globalData.userInfo.avatarUrl,
        content: commentText,
        userid: app.globalData.userid,
        replyid:replyid,
        replynickname:replynickname
      },
      success: res => {
        let rdata = res.data;
        //console.log(JSON.parse(rdata))
        let jsonstr = rdata.substring(rdata.indexOf("data") + 6, rdata.length - 1);
        let reg = /\\/g;
        //使用replace方法将全部匹配正则表达式的转义符替换为空
        jsonstr = jsonstr.replace(reg, '');
        let tres = JSON.parse(jsonstr);
        tres._id = tres.id;
        resolve({data:tres});
      },
      fail: res => {
        reject({msg:'FAILED_TO_COMMENT'});
      }
    })
  })
}
function UpThumbInfo(cid){
  let app = getApp();
  let nickname = wx.getStorageSync('wxuserinfo').nickName || '找不到'
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain + '/thumb',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        createtime: timeutil.TimeCode(new Date()),
        circleid: cid,
        userid: app.globalData.userid,
        nickname:nickname
      },
      success: res => {
        let rdata = res.data;
        //console.log(JSON.parse(rdata))
        let jsonstr = rdata.substring(rdata.indexOf("data") + 6, rdata.length - 1);
        let reg = /\\/g;
        //使用replace方法将全部匹配正则表达式的转义符替换为空
        jsonstr = jsonstr.replace(reg, '');
        let tres = JSON.parse(jsonstr);
        tres._id = tres.id;
        //console.log(tres);
        resolve({data:tres})
      },
      fail: res => {
        reject({msg:'FAILED_TO_LIKE'});
      }
    })

  })
}
function AuthUserPri(){
  let app = getApp();
  let openid = app.globalData.openid;
  let userid = app.globalData.userid;
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'custom/'+userid,
      method:'GET',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success:res=>{
        let tres= JSON.parse(res.data).data;
        resolve(tres);
      },fail:res=>{
        console.log(res)
        reject({msg:'FAILED_TO_LOAD_AUTH'})
      }
    })
  })
}
//提交鉴定请求
function UpAuthReq(userinfo){
  let app = getApp();
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'custom',
      method:'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data:{
        nickname: userinfo.nickName,
        avatar: userinfo.avatarUrl,
        userid:app.globalData.userid
      },
      success:res=>{
        let tres= JSON.parse(res.data).data;
        resolve(tres);
      },
      fail:res=>{
        reject({msg:'UP_AUTH_FAILED'});
      }
    })
  })
}
//
function GetAuthUserStatus(status){
  let app = getApp();
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'custom',
      method:'GET',
      data:{
        status:status
      },
      success:res=>{
        //console.log(res)
        let tres = JSON.parse(res.data).data;
        resolve(tres)
      },
      fail:res=>{
        console.log(res)
        reject({msg:'无法获取审核列表'})
      }
    })
  })
}
function EditAuthStatus(id,status){
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'customedit',
      method:'POST',
      data:{
        id:id,
        status:status
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success:res=>{
        let tres = JSON.parse(res.data);
        resolve({data:tres.data})
      },
      fail:res=>{
        console.log(res)
        reject({msg:'修改状态失败'})
      }
    })
  })
}
function DelCircleInfo(id){
  return new Promise(function(resolve,reject){
    wx.request({
      url: Config.SevDomain+'circledel/'+id,
      method:'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success:res=>{
        resolve(res)
      },
      fail:res=>{
        reject({msg:'FAILED_LOAD_DEL_ACTION'})
      }
    })
  })
}
module.exports = {
  GetOpenData,
  UploadImage,
  UpCircleInfo,
  QueryCircleInfo,
  GetOneCircleInfo,
  GetCommentInfo,
  GetThumbInfo,
  UpCommentInfo,
  UpThumbInfo,
  AuthUserPri,
  UpAuthReq,
  GetAuthUserStatus,
  EditAuthStatus,
  DelCircleInfo
}